<?php

namespace App\Console\Commands;

use App\Libraries\Claude;
use App\Libraries\GeMini;
use App\Libraries\MicrosoftSpeech;
use App\Models\ChapterData;
use App\Models\MicrosoftVoice;
use App\Services\AudioBookJobService;
use App\Services\AudioBookService;
use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;

class DataHandle extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:data-handle';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $microsoftSpeech = new MicrosoftSpeech;

        $voice_roles = MicrosoftVoice::orderBy('gender')->pluck('short_name', 'display_name');

        $file_path = '/Users/guoqikai/Downloads/有情感/5/19.txt';
        $file_name = pathinfo($file_path, PATHINFO_FILENAME);

        $handle = fopen($file_path, 'r');

        $texts = [];
        while (($line = fgets($handle)) !== false) {
            $line = trim($line, "\n");
            if (empty($line)) {
                continue;
            }
            $texts[] = $line;
        }
        $texts = array_values($texts);

        fclose($handle);

        $ssml_data = [];
        foreach ($texts as $text) {
            if (empty($text)) {
                continue;
            }
            $pattern = '/【(.*?)】/';
            if (preg_match($pattern, $text, $matches)) {
                $profile = trim($matches[1]);
                $content = trim(str_replace($matches[0], '', $text));
            } else {
                dd('未找到角色 ' . $text);
            }
            $content = trim(trim($content, '：'), ':');
            $content = str_replace("\u{A0}", '', $content);
            if (empty($profile) || empty($content)) {
                dd('角色或内容为空');
            }

            $short_name = $voice_roles[$profile] ?? '';
            if (empty($short_name)) {
                // 角色名与音色库未对应上
                $profile = str_replace(' ', '', $profile);
                $short_name = $voice_roles[$profile] ?? '';
            }
            if (empty($short_name)) {
                dd('未找到语音');
            }

            $pattern = '/\((.*?)\)/';
            preg_match_all($pattern, $content, $matches);
            $styles = [];
            foreach ($matches[1] as $val) {
                $styles[] = $val;
            }
            $styles = !empty($styles) ? array_unique($styles) : [];
            $speed = '0%';
            $voice_label = '<voice name="' . $short_name . '">';
            if (!empty($styles)) {
                foreach ($styles as $style) {
                    $pattern = '/\(' . $style . '\)(.*?)\(' . $style . '\)/';
                    if (preg_match($pattern, $content, $matches)) {
                        $voice_label .= '<s /><mstts:express-as style="' . $style . '"><prosody rate="' . $speed . '">' . $matches[1] . '</prosody></mstts:express-as><s />';
                    } else {
                        $voice_label .= '<prosody rate="' . $speed . '">' . $content . '</prosody>';
                    }
                }
            } else {
                $voice_label .= '<prosody rate="' . $speed . '">' . $content . '</prosody>';
            }

            $voice_label .= '</voice>';
            $ssml_data[] = $voice_label;
        }

        $limit = 45;
        $length = count($ssml_data);
        if ($length > $limit) {
            $page = ceil($length / $limit);
            $file_list = [];
            for ($i = 0; $i < $page; $i++) {
                $offset = $i * $limit;
                $list = array_slice($ssml_data, $offset, $limit);
                $ssml = '<speak xmlns="http://www.w3.org/2001/10/synthesis" xmlns:mstts="http://www.w3.org/2001/mstts" xmlns:emo="http://www.w3.org/2009/10/emotionml" version="1.0" xml:lang="en-US">';
                $ssml .= implode('', $list);
                $ssml .= '</speak>';

                $resource = $microsoftSpeech->textToSpeech($ssml);
                $output = '/Users/guoqikai/Htdocs/audiobook/demo4/' . $file_name . '_' . $i . '.wav';
                file_put_contents($output, $resource);
                if (check_media_file($output) === false) {
                    dd($output);
                }
                $file_list[] = $output;
                merge_audio($file_list, '/Users/guoqikai/Htdocs/audiobook/demo4/' . $file_name . '.wav');
                unset($ssml);
            }
        } else {
            $ssml = '<speak xmlns="http://www.w3.org/2001/10/synthesis" xmlns:mstts="http://www.w3.org/2001/mstts" xmlns:emo="http://www.w3.org/2009/10/emotionml" version="1.0" xml:lang="en-US">';
            $ssml .= implode('', $ssml_data);
            $ssml .= '</speak>';

            $resource = $microsoftSpeech->textToSpeech($ssml);
            $output = '/Users/guoqikai/Htdocs/audiobook/demo4/' . $file_name . '.wav';
            file_put_contents($output, $resource);
            if (check_media_file($output) === false) {
                dd($output);
            }
            unset($ssml);
        }
    }
}
